/**
 * @file snakegamemanager.cpp
 * @brief Snake游戏管理器类实现文件
 *
 * 实现Snake游戏管理器的所有功能，包括：
 * - 游戏组件的初始化和协调
 * - 连接管理和状态控制
 * - 房间管理和游戏控制
 * - 事件处理和信号转发
 * - 统计信息和配置管理
 */

#include "../include/snakegamemanager.h"
#include "../include/config.h"
#include <QDebug>               // 调试输出
#include <QDateTime>            // 时间处理

/**
 * @brief SnakeGameManager构造函数
 * @param parent 父对象指针
 *
 * 初始化Snake游戏管理器：
 * 1. 创建核心组件
 * 2. 建立信号槽连接
 * 3. 设置默认状态
 */
SnakeGameManager::SnakeGameManager(QObject *parent)
    : QObject(parent)
    , m_gameState(new SnakeGameState(this))
    , m_webSocketClient(new WebSocketClient(this))
    , m_apiClient(new SnakeApiClient(this))
    , m_connectionStatus(Disconnected)
    , m_connectTime(0)
    , m_reconnectAttempts(0)
{
    // === 建立WebSocket信号槽连接 ===
    connect(m_webSocketClient, &WebSocketClient::connected,
            this, &SnakeGameManager::onWebSocketConnected);
    connect(m_webSocketClient, &WebSocketClient::disconnected,
            this, &SnakeGameManager::onWebSocketDisconnected);
    connect(m_webSocketClient, &WebSocketClient::connectionError,
            this, &SnakeGameManager::onWebSocketError);
    connect(m_webSocketClient, &WebSocketClient::gameError,
            this, &SnakeGameManager::onWebSocketGameError);
    connect(m_webSocketClient, &WebSocketClient::authenticated,
            this, &SnakeGameManager::onWebSocketAuthenticated);
    connect(m_webSocketClient, &WebSocketClient::authenticationFailed,
            this, &SnakeGameManager::onWebSocketAuthenticationFailed);
    connect(m_webSocketClient, &WebSocketClient::gameStateUpdated,
            this, &SnakeGameManager::onWebSocketGameStateUpdated);
    connect(m_webSocketClient, &WebSocketClient::playerJoined,
            this, &SnakeGameManager::onWebSocketPlayerJoined);
    connect(m_webSocketClient, &WebSocketClient::playerLeft,
            this, &SnakeGameManager::onWebSocketPlayerLeft);
    connect(m_webSocketClient, &WebSocketClient::roomCreated,
            this, &SnakeGameManager::onWebSocketRoomCreated);
    connect(m_webSocketClient, &WebSocketClient::roomJoined,
            this, &SnakeGameManager::onWebSocketRoomJoined);
    connect(m_webSocketClient, &WebSocketClient::chatMessageReceived,
            this, &SnakeGameManager::onWebSocketChatMessageReceived);
    connect(m_webSocketClient, &WebSocketClient::gameStarted,
            this, [this]() {
                QJsonObject emptyData;
                onWebSocketGameStarted(emptyData);
            });
    connect(m_webSocketClient, &WebSocketClient::gameEnded,
            this, &SnakeGameManager::onWebSocketGameEnded);

    // === 建立API客户端信号槽连接 ===
    connect(m_apiClient, &SnakeApiClient::gameServersReceived,
            this, &SnakeGameManager::onApiGameServersReceived);
    connect(m_apiClient, &SnakeApiClient::gameLoginSucceeded,
            this, &SnakeGameManager::onApiGameLoginSucceeded);
    connect(m_apiClient, &SnakeApiClient::gameLoginFailed,
            this, &SnakeGameManager::onApiGameLoginFailed);
    connect(m_apiClient, &SnakeApiClient::roomListReceived,
            this, &SnakeGameManager::onApiRoomListReceived);
    connect(m_apiClient, &SnakeApiClient::playerStatsReceived,
            this, &SnakeGameManager::onApiPlayerStatsReceived);
    connect(m_apiClient, &SnakeApiClient::leaderboardReceived,
            this, &SnakeGameManager::onApiLeaderboardReceived);
    connect(m_apiClient, &SnakeApiClient::gameHistoryReceived,
            this, &SnakeGameManager::onApiGameHistoryReceived);
    connect(m_apiClient, &SnakeApiClient::gameConfigReceived,
            this, &SnakeGameManager::onApiGameConfigReceived);
    connect(m_apiClient, &SnakeApiClient::apiError,
            this, &SnakeGameManager::onApiError);

    // === 建立游戏状态信号槽连接 ===
    connect(m_gameState, &SnakeGameState::stateUpdated,
            this, [this]() {
                // 创建一个空的游戏状态对象，实际数据将通过WebSocket接收
                QJsonObject gameState;
                emit gameStateUpdated(gameState);
            });

    qDebug() << "SnakeGameManager initialized";
}

/**
 * @brief SnakeGameManager析构函数
 */
SnakeGameManager::~SnakeGameManager()
{
    disconnectFromGameServer();
    qDebug() << "SnakeGameManager destroyed";
}

/**
 * @brief 初始化游戏管理器
 * @param apiGatewayUrl API网关URL
 * @param accessToken 访问令牌
 */
void SnakeGameManager::initialize(const QString &apiGatewayUrl, const QString &accessToken)
{
    qDebug() << "Initializing SnakeGameManager with API Gateway:" << apiGatewayUrl;
    
    // === 设置API客户端 ===
    m_apiClient->setApiGatewayUrl(apiGatewayUrl);
    m_apiClient->setAccessToken(accessToken);
    
    // === 重置状态 ===
    resetState();
    
    qDebug() << "SnakeGameManager initialization completed";
}

/**
 * @brief 设置当前玩家信息
 * @param playerId 玩家ID
 * @param playerName 玩家名称
 */
void SnakeGameManager::setPlayerInfo(const QString &playerId, const QString &playerName)
{
    m_currentPlayerId = playerId;
    m_currentPlayerName = playerName;
    m_gameState->setCurrentPlayerId(playerId);
    
    qDebug() << "Player info set - ID:" << playerId << "Name:" << playerName;
}

/**
 * @brief 连接到游戏服务器
 * @param preferredServerId 首选服务器ID（可选）
 * @param region 首选地区（可选）
 */
void SnakeGameManager::connectToGameServer(const QString &preferredServerId, const QString &region)
{
    if (m_connectionStatus != Disconnected) {
        qWarning() << "Already connected or connecting to game server";
        return;
    }
    
    qDebug() << "Connecting to game server, preferred server:" << preferredServerId << "region:" << region;
    
    setConnectionStatus(Connecting);
    
    // === 首先获取可用服务器列表 ===
    m_apiClient->getAvailableGameServers(region, "snake");
    
    // === 保存首选服务器信息 ===
    if (!preferredServerId.isEmpty()) {
        m_recommendedServerId = preferredServerId;
    }
}

/**
 * @brief 断开游戏服务器连接
 */
void SnakeGameManager::disconnectFromGameServer()
{
    qDebug() << "Disconnecting from game server";
    
    // === 断开WebSocket连接 ===
    if (m_webSocketClient->isConnected()) {
        m_webSocketClient->disconnectFromServer("User requested disconnect");
    }
    
    // === 重置状态 ===
    resetState();
    setConnectionStatus(Disconnected);
    
    emit disconnected("User requested disconnect");
}

/**
 * @brief 获取房间列表
 * @param status 房间状态筛选（可选）
 * @param gameMode 游戏模式筛选（可选）
 */
void SnakeGameManager::getRoomList(const QString &status, int gameMode)
{
    qDebug() << "Requesting room list, status:" << status << "gameMode:" << gameMode;
    m_apiClient->getRoomList(status, gameMode);
}

/**
 * @brief 创建房间
 * @param config 房间配置
 */
void SnakeGameManager::createRoom(const GameConfig &config)
{
    if (m_connectionStatus != InGame) {
        qWarning() << "Cannot create room: not connected to game server";
        return;
    }
    
    qDebug() << "Creating room:" << config.roomName;
    
    // === 构建房间配置JSON ===
    QJsonObject roomConfig;
    roomConfig["max_players"] = config.maxPlayers;
    roomConfig["game_mode"] = config.gameMode;
    roomConfig["map_width"] = config.mapWidth;
    roomConfig["map_height"] = config.mapHeight;
    roomConfig["game_speed_ms"] = config.gameSpeedMs;
    roomConfig["enable_walls"] = config.enableWalls;
    roomConfig["enable_special_foods"] = config.enableSpecialFoods;
    roomConfig["max_food_count"] = config.maxFoodCount;
    
    // === 通过WebSocket创建房间 ===
    m_webSocketClient->createRoom(config.roomName, roomConfig);
}

/**
 * @brief 加入房间
 * @param roomId 房间ID
 */
void SnakeGameManager::joinRoom(const QString &roomId)
{
    if (m_connectionStatus != InGame) {
        qWarning() << "Cannot join room: not connected to game server";
        return;
    }
    
    qDebug() << "Joining room:" << roomId;
    m_webSocketClient->joinRoom(roomId);
}

/**
 * @brief 离开房间
 */
void SnakeGameManager::leaveRoom()
{
    if (m_connectionStatus != InGame) {
        qWarning() << "Cannot leave room: not connected to game server";
        return;
    }
    
    qDebug() << "Leaving current room";
    m_webSocketClient->leaveRoom();
    emit roomLeft();
}

/**
 * @brief 获取当前房间ID
 * @return 当前房间ID
 */
QString SnakeGameManager::getCurrentRoomId() const
{
    return m_gameState->getRoomId();
}

/**
 * @brief 改变移动方向
 * @param direction 新方向（0=上，1=右，2=下，3=左）
 */
void SnakeGameManager::changeDirection(int direction)
{
    if (m_connectionStatus != InGame) {
        qWarning() << "Cannot change direction: not connected to game server";
        return;
    }
    
    // === 验证方向值 ===
    if (direction < 0 || direction > 3) {
        qWarning() << "Invalid direction:" << direction;
        return;
    }
    
    m_webSocketClient->changeDirection(direction);
}

/**
 * @brief 改变移动方向（使用枚举）
 * @param direction 新方向
 */
void SnakeGameManager::changeDirection(Direction direction)
{
    changeDirection(static_cast<int>(direction));
}

/**
 * @brief 发送聊天消息
 * @param message 聊天内容
 */
void SnakeGameManager::sendChatMessage(const QString &message)
{
    if (m_connectionStatus != InGame) {
        qWarning() << "Cannot send chat message: not connected to game server";
        return;
    }
    
    if (message.trimmed().isEmpty()) {
        qWarning() << "Cannot send empty chat message";
        return;
    }
    
    m_webSocketClient->sendChatMessage(message);
}

/**
 * @brief 获取当前玩家的蛇数据
 * @return 当前玩家蛇数据指针，如果不存在返回nullptr
 */
const SnakeData* SnakeGameManager::getCurrentPlayerSnake() const
{
    return m_gameState->getCurrentPlayerSnake();
}

/**
 * @brief 获取游戏统计信息
 * @return 统计信息JSON对象
 */
QJsonObject SnakeGameManager::getGameStats() const
{
    QJsonObject stats;
    stats["connection_status"] = static_cast<int>(m_connectionStatus);
    stats["current_player_id"] = m_currentPlayerId;
    stats["current_room_id"] = getCurrentRoomId();
    stats["connect_time"] = m_connectTime;
    stats["reconnect_attempts"] = m_reconnectAttempts;
    
    // === 添加游戏状态统计 ===
    stats["game_status"] = static_cast<int>(m_gameState->getGameStatus());
    stats["player_count"] = m_gameState->getPlayerCount();
    stats["alive_snake_count"] = m_gameState->getAliveSnakeCount();
    stats["food_count"] = m_gameState->getFoodCount();
    stats["tick_count"] = m_gameState->getTickCount();
    
    // === 添加当前玩家蛇统计 ===
    const SnakeData* playerSnake = getCurrentPlayerSnake();
    if (playerSnake) {
        stats["player_score"] = playerSnake->score;
        stats["player_length"] = playerSnake->length;
        stats["player_alive"] = playerSnake->isAlive;
    }
    
    // === 添加WebSocket连接统计 ===
    QJsonObject wsStats = m_webSocketClient->getConnectionStats();
    stats["websocket_stats"] = wsStats;
    
    return stats;
}

/**
 * @brief 获取玩家统计信息
 */
void SnakeGameManager::getPlayerStats()
{
    qDebug() << "Requesting player stats";
    m_apiClient->getPlayerStats();
}

/**
 * @brief 获取排行榜
 * @param type 排行榜类型
 */
void SnakeGameManager::getLeaderboard(const QString &type)
{
    qDebug() << "Requesting leaderboard, type:" << type;
    m_apiClient->getLeaderboard(type);
}

/**
 * @brief 获取游戏历史记录
 */
void SnakeGameManager::getGameHistory()
{
    qDebug() << "Requesting game history";
    m_apiClient->getGameHistory();
}

/**
 * @brief 获取游戏配置
 */
void SnakeGameManager::getGameConfig()
{
    qDebug() << "Requesting game config";
    m_apiClient->getGameConfig();
}

/**
 * @brief 更新玩家配置
 * @param config 玩家配置
 */
void SnakeGameManager::updatePlayerConfig(const QJsonObject &config)
{
    qDebug() << "Updating player config";
    m_apiClient->updatePlayerConfig(config);
}

/**
 * @brief WebSocket连接成功处理
 */
void SnakeGameManager::onWebSocketConnected()
{
    qDebug() << "WebSocket connected successfully";
    setConnectionStatus(Connected);
    emit connected();
}

/**
 * @brief WebSocket断开连接处理
 * @param reason 断开原因
 */
void SnakeGameManager::onWebSocketDisconnected(const QString &reason)
{
    qDebug() << "WebSocket disconnected, reason:" << reason;
    setConnectionStatus(Disconnected);
    emit disconnected(reason);
}

/**
 * @brief WebSocket连接错误处理
 * @param error 错误信息
 */
void SnakeGameManager::onWebSocketError(const QString &error)
{
    qWarning() << "WebSocket error:" << error;
    setConnectionStatus(Error);
    emit connectionError(error);
}

/**
 * @brief WebSocket游戏错误处理
 * @param errorCode 错误代码
 * @param errorMessage 错误消息
 */
void SnakeGameManager::onWebSocketGameError(const QString &errorCode, const QString &errorMessage)
{
    qDebug() << "SnakeGameManager: 收到游戏错误:" << errorCode << "-" << errorMessage;

    // 游戏业务错误不应该影响连接状态
    // 只记录日志，不触发连接错误
    if (errorCode == "NO_PERMISSION") {
        qDebug() << "SnakeGameManager: 权限错误，可能是重复的start_game请求，忽略";
    } else {
        qWarning() << "SnakeGameManager: 未处理的游戏错误:" << errorCode << "-" << errorMessage;
    }
}

/**
 * @brief WebSocket认证成功处理
 * @param playerInfo 玩家信息
 */
void SnakeGameManager::onWebSocketAuthenticated(const QJsonObject &playerInfo)
{
    qDebug() << "WebSocket authentication successful";
    setConnectionStatus(InGame);

    // === 更新玩家信息 ===
    if (playerInfo.contains("player_id")) {
        m_currentPlayerId = playerInfo["player_id"].toString();
        m_gameState->setCurrentPlayerId(m_currentPlayerId);
    }

    qDebug() << "Ready for game, player ID:" << m_currentPlayerId;

    // === 发出认证成功信号 ===
    emit authenticated(playerInfo);
}

/**
 * @brief WebSocket认证失败处理
 * @param error 错误信息
 */
void SnakeGameManager::onWebSocketAuthenticationFailed(const QString &error)
{
    qWarning() << "WebSocket authentication failed:" << error;
    setConnectionStatus(Error);
    emit connectionError(QString("Authentication failed: %1").arg(error));

    // === 发出认证失败信号 ===
    emit authenticationFailed(error);
}

/**
 * @brief WebSocket游戏状态更新处理
 * @param gameState 游戏状态
 */
void SnakeGameManager::onWebSocketGameStateUpdated(const QJsonObject &gameState)
{
    // === 先发出游戏状态更新信号，确保原始数据不被修改 ===
    emit gameStateUpdated(gameState);

    // === 然后更新内部游戏状态（可能会修改数据） ===
    m_gameState->updateFromJson(gameState);

    // === 更新统计信息 ===
    updateGameStats();
}

/**
 * @brief WebSocket玩家加入处理
 * @param playerId 玩家ID
 * @param playerName 玩家名称
 */
void SnakeGameManager::onWebSocketPlayerJoined(const QString &playerId, const QString &playerName)
{
    qDebug() << "Player joined:" << playerName << "(" << playerId << ")";
    emit playerJoined(playerId, playerName);
}

/**
 * @brief WebSocket玩家离开处理
 * @param playerId 玩家ID
 */
void SnakeGameManager::onWebSocketPlayerLeft(const QString &playerId)
{
    qDebug() << "Player left:" << playerId;
    emit playerLeft(playerId);
}

/**
 * @brief WebSocket房间创建处理
 * @param roomId 房间ID
 * @param roomInfo 房间信息
 */
void SnakeGameManager::onWebSocketRoomCreated(const QString &roomId, const QJsonObject &roomInfo)
{
    qDebug() << "SnakeGameManager: 房间创建成功:" << roomId;

    // === 发出房间创建信号 ===
    emit roomCreated(roomId);
}

/**
 * @brief WebSocket加入房间处理
 * @param roomId 房间ID
 */
void SnakeGameManager::onWebSocketRoomJoined(const QString &roomId)
{
    qDebug() << "Joined room:" << roomId;
    emit roomJoined(roomId);
}

/**
 * @brief WebSocket聊天消息处理
 * @param senderId 发送者ID
 * @param senderName 发送者名称
 * @param message 消息内容
 */
void SnakeGameManager::onWebSocketChatMessageReceived(const QString &senderId, const QString &senderName, const QString &message)
{
    emit chatMessageReceived(senderId, senderName, message);
}

/**
 * @brief WebSocket游戏开始处理
 * @param gameData 游戏开始数据
 */
void SnakeGameManager::onWebSocketGameStarted(const QJsonObject &gameData)
{
    qDebug() << "SnakeGameManager: 游戏开始";
    setConnectionStatus(InGame);
    emit gameStarted(gameData);
}

/**
 * @brief WebSocket游戏结束处理
 * @param endData 游戏结束数据
 */
void SnakeGameManager::onWebSocketGameEnded(const QJsonObject &endData)
{
    qDebug() << "SnakeGameManager: 游戏结束";
    setConnectionStatus(Connected);
    emit gameEnded(endData);
}

/**
 * @brief API游戏服务器列表获取处理
 * @param servers 服务器列表
 * @param recommendedServerId 推荐服务器ID
 */
void SnakeGameManager::onApiGameServersReceived(const QList<SnakeApiClient::GameServerInfo> &servers, const QString &recommendedServerId)
{
    qDebug() << "Received" << servers.size() << "game servers, recommended:" << recommendedServerId;

    m_availableServers = servers;
    if (!recommendedServerId.isEmpty()) {
        m_recommendedServerId = recommendedServerId;
    }

    emit gameServersReceived(servers);

    // === 自动执行游戏登录 ===
    QString preferredServerId = m_recommendedServerId.isEmpty() ? recommendedServerId : m_recommendedServerId;
    performGameLogin(preferredServerId, QString());
}

/**
 * @brief API游戏登录成功处理
 * @param loginResult 登录结果
 */
void SnakeGameManager::onApiGameLoginSucceeded(const SnakeApiClient::GameLoginResult &loginResult)
{
    qDebug() << "Game login successful, server:" << loginResult.serverInfo.serverId;

    // === 保存登录信息 ===
    m_currentGameToken = loginResult.sessionToken; // 使用session_token
    m_currentSessionId = loginResult.sessionId;
    m_currentServer = loginResult.serverInfo;

    // === 连接WebSocket ===
    connectWebSocket(loginResult);

    emit gameLoginSucceeded(loginResult);
}

/**
 * @brief API游戏登录失败处理
 * @param error 错误信息
 */
void SnakeGameManager::onApiGameLoginFailed(const QString &error)
{
    qWarning() << "Game login failed:" << error;
    setConnectionStatus(Error);
    emit gameLoginFailed(error);
}

/**
 * @brief API房间列表获取处理
 * @param rooms 房间列表
 * @param totalCount 总房间数
 */
void SnakeGameManager::onApiRoomListReceived(const QList<SnakeApiClient::RoomInfo> &rooms, int totalCount)
{
    qDebug() << "Received" << rooms.size() << "rooms, total:" << totalCount;
    emit roomListReceived(rooms);
}

/**
 * @brief API玩家统计信息获取处理
 * @param stats 玩家统计信息
 */
void SnakeGameManager::onApiPlayerStatsReceived(const SnakeApiClient::PlayerStats &stats)
{
    qDebug() << "Received player stats for:" << stats.username;
    emit playerStatsReceived(stats);
}

/**
 * @brief API排行榜获取处理
 * @param leaderboard 排行榜数据
 * @param type 排行榜类型
 */
void SnakeGameManager::onApiLeaderboardReceived(const QJsonArray &leaderboard, const QString &type)
{
    qDebug() << "Received leaderboard with" << leaderboard.size() << "entries, type:" << type;
    emit leaderboardReceived(leaderboard, type);
}

/**
 * @brief API游戏历史记录获取处理
 * @param history 历史记录数据
 */
void SnakeGameManager::onApiGameHistoryReceived(const QJsonArray &history)
{
    qDebug() << "Received game history with" << history.size() << "entries";
    emit gameHistoryReceived(history);
}

/**
 * @brief API游戏配置获取处理
 * @param config 游戏配置
 */
void SnakeGameManager::onApiGameConfigReceived(const QJsonObject &config)
{
    qDebug() << "Received game config";
    emit gameConfigReceived(config);
}

/**
 * @brief API错误处理
 * @param endpoint API端点
 * @param error 错误信息
 */
void SnakeGameManager::onApiError(const QString &endpoint, const QString &error)
{
    qWarning() << "API error for endpoint" << endpoint << ":" << error;

    // === 根据端点类型处理错误 ===
    if (endpoint.contains("/auth/game/login")) {
        setConnectionStatus(Error);
        emit gameLoginFailed(error);
    } else {
        emit connectionError(QString("API Error [%1]: %2").arg(endpoint, error));
    }
}

/**
 * @brief 设置连接状态
 * @param status 新状态
 */
void SnakeGameManager::setConnectionStatus(ConnectionStatus status)
{
    if (m_connectionStatus != status) {
        ConnectionStatus oldStatus = m_connectionStatus;
        m_connectionStatus = status;

        qDebug() << "Connection status changed from" << static_cast<int>(oldStatus)
                 << "to" << static_cast<int>(status);
        emit connectionStatusChanged(status);
    }
}

/**
 * @brief 执行游戏登录
 * @param preferredServerId 首选服务器ID
 * @param region 地区
 */
void SnakeGameManager::performGameLogin(const QString &preferredServerId, const QString &region)
{
    qDebug() << "Performing game login, preferred server:" << preferredServerId;

    // === 构建客户端信息 ===
    QJsonObject clientInfo;
    clientInfo["player_name"] = m_currentPlayerName;
    clientInfo["preferred_region"] = region;

    m_apiClient->gameLogin("snake", preferredServerId, clientInfo);
}

/**
 * @brief 连接WebSocket
 * @param loginResult 登录结果
 */
void SnakeGameManager::connectWebSocket(const SnakeApiClient::GameLoginResult &loginResult)
{
    qDebug() << "Connecting to WebSocket:" << loginResult.websocketUrl;

    // === 构建WebSocket连接配置 ===
    WebSocketClient::ConnectionConfig config;
    config.serverUrl = loginResult.websocketUrl;
    config.gameToken = loginResult.sessionToken;    // 用于Authorization头
    config.sessionToken = loginResult.sessionToken; // 用于认证消息
    config.playerId = loginResult.playerId;
    config.heartbeatInterval = 30000;
    config.reconnectInterval = 5000;
    config.maxReconnectAttempts = 5;
    config.enableCompression = true;
    config.enableSSL = loginResult.websocketUrl.startsWith("wss://");

    // === 开始WebSocket连接 ===
    bool success = m_webSocketClient->connectToServer(config);
    if (!success) {
        qWarning() << "Failed to start WebSocket connection";
        setConnectionStatus(Error);
        emit connectionError("Failed to start WebSocket connection");
    }
}

/**
 * @brief 重置状态
 */
void SnakeGameManager::resetState()
{
    m_currentGameToken.clear();
    m_currentSessionId.clear();
    m_availableServers.clear();
    m_recommendedServerId.clear();
    m_connectTime = 0;
    m_reconnectAttempts = 0;

    // === 重置游戏状态 ===
    m_gameState->clear();
}

/**
 * @brief 更新游戏统计信息
 */
void SnakeGameManager::updateGameStats()
{
    // === 更新连接时间 ===
    if (m_connectTime == 0 && m_connectionStatus == InGame) {
        m_connectTime = QDateTime::currentMSecsSinceEpoch();
    }

    // === 这里可以添加其他统计信息的更新逻辑 ===
}

/**
 * @brief 直接连接WebSocket服务器（新业务流程）
 * @param config WebSocket连接配置
 * @return 是否成功开始连接
 */
bool SnakeGameManager::connectToWebSocket(const WebSocketConfig &config)
{
    qDebug() << "SnakeGameManager: 开始直接连接WebSocket服务器";
    qDebug() << "  URL:" << config.url;
    qDebug() << "  playerId:" << config.playerId;
    qDebug() << "  playerName:" << config.playerName;
    qDebug() << "  clientType:" << config.clientType;

    // === 保存配置信息 ===
    m_currentPlayerId = config.playerId;
    m_currentPlayerName = config.playerName;

    // === 设置连接状态 ===
    setConnectionStatus(Connecting);

    // === 构建WebSocketClient连接配置 ===
    WebSocketClient::ConnectionConfig wsConfig;
    wsConfig.serverUrl = config.url;
    wsConfig.gameToken = config.gameToken;      // access_token用于连接头
    wsConfig.sessionToken = config.sessionToken; // session_token用于消息认证
    wsConfig.playerId = config.playerId;
    wsConfig.heartbeatInterval = config.heartbeatInterval;
    wsConfig.reconnectInterval = 5000;
    wsConfig.maxReconnectAttempts = config.maxReconnectAttempts;
    wsConfig.enableCompression = true;
    wsConfig.enableSSL = config.url.startsWith("wss://");

    // === 添加协议支持（根据实际握手信息，服务器支持snake-game-v1） ===
    wsConfig.protocols << "snake-game-v1";

    // === 开始WebSocket连接 ===
    bool success = m_webSocketClient->connectToServer(wsConfig);
    if (!success) {
        qWarning() << "SnakeGameManager: 无法开始WebSocket连接";
        setConnectionStatus(Error);
        emit connectionError("无法开始WebSocket连接");
        return false;
    }

    qDebug() << "SnakeGameManager: WebSocket连接请求已发送";
    return true;
}

bool SnakeGameManager::sendMessage(const QJsonObject &message)
{
    if (!m_webSocketClient) {
        qDebug() << "SnakeGameManager: WebSocket客户端未初始化";
        return false;
    }

    if (m_connectionStatus != InGame && m_connectionStatus != Connected) {
        qDebug() << "SnakeGameManager: WebSocket未连接，无法发送消息";
        return false;
    }

    // 发送JSON消息
    bool success = m_webSocketClient->sendMessage(message);
    if (success) {
        qDebug() << "SnakeGameManager: 消息发送成功，类型:" << message["type"].toString();
    } else {
        qDebug() << "SnakeGameManager: 消息发送失败，类型:" << message["type"].toString();
    }

    return success;
}
